package com.avecsys.quotemanager.dao.user;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.dao.common.BaseDAOImpl;
import com.avecsys.quotemanager.dao.common.EnumDBRecordStatus;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.DAOException;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;

public class UserMasterDAOImpl extends BaseDAOImpl implements UserMasterDAO {

	private static final Log log = LogFactory.getLog(UserMasterDAOImpl.class);

	/**
	 * Method to find all the list of users for a supplier
	 * 
	 * @param supplierMasterPojo
	 * @return List<UserMasterPojo>
	 * @throws BusinessException
	 */
	@Override
	public List<UserMasterPojo> findAllUsersBySupplier(
			final SupplierMasterPojo supplierMasterPojo) throws DAOException {
		return getHibernateTemplate().execute(
				new HibernateCallback<List<UserMasterPojo>>() {
					@Override
					public List<UserMasterPojo> doInHibernate(Session session)
							throws HibernateException, SQLException {
						final Criteria criteria = session
								.createCriteria(UserMasterPojo.class);
						criteria.add(Expression.eq(
								"supplierMasterPojo.supplierId",
								supplierMasterPojo.getSupplierId()));
						criteria.add(Expression.eq("status",
								EnumDBRecordStatus.ACTIVE.status()));
						return (List<UserMasterPojo>) criteria.list();
					}
				});
	}

	/**
	 * Method to return all the Administrator users for a supplier
	 * 
	 * @param supplierMasterPojo
	 * @return boolean
	 * @throws DAOException
	 */
	@Override
	public List<UserMasterPojo> findAllSupplierAdminUsers(
			final SupplierMasterPojo supplierMasterPojo) throws DAOException {
		return getHibernateTemplate().execute(
				new HibernateCallback<List<UserMasterPojo>>() {
					@Override
					public List<UserMasterPojo> doInHibernate(Session session)
							throws HibernateException, SQLException {
						final Criteria criteria = session
								.createCriteria(UserMasterPojo.class);
						criteria.add(Expression.eq(
								"supplierMasterPojo.supplierId",
								supplierMasterPojo.getSupplierId()));
						criteria.add(Expression.eq("isAdmin",
								Boolean.TRUE.toString()));
						criteria.add(Expression.eq("status",
								EnumDBRecordStatus.ACTIVE.status()));
						return (List<UserMasterPojo>) criteria.list();
					}
				});
	}
}
